<template>
  <video
    ref="myPlayer"
    class="myPlayer video-js vjs-default-skin"
    :preload="options.preload"
  >
    <source :src="src" :type="sourceType" :autoplay="options.autoplay" :controls="options.controls" :muted="options.muted" :loop="options.loop">
  </video>
</template>  

<script>
import "video.js/dist/video-js.min.css";
import videojs from "video.js";
import "videojs-contrib-hls";
export default {
  props: {
    src: {
      default: "",
    },
    options: {
      default: () => {
        return {
          autoplay: true, // 设置自动播放
          loop: true, // 设置循环播放
          muted: true, // 设置了它为true，才可实现自动播放,同时视频也被静音 （Chrome66及以上版本，禁止音视频的自动播放）
          preload: "auto", // 预加载
          controls: true, // 显示播放的控件
        };
      },
    },
  },
  data() {
    return {
      player: null,
    };
  },
  computed: {
    sourceType() {
      let srcArr = this.src.split(".");
      let type = srcArr[srcArr.length - 1];
      switch (type) {
        case "mp4":
        case "webm":
          return `video/${type}`;
        case "ogv":
          return `video/ogg`;
        default:
          return `application/x-mpegURL`; // 告诉videojs,这是一个hls流
      }
    },
  },
  mounted() {
    // 渲染视频
    this.player = videojs(this.$refs.myPlayer, this.options);
  },
  beforeDestroy() {
    this.player && this.player.dispose();
  },
};
</script>
<style scoped lang="scss">
.myPlayer {
  flex: 1 1 auto;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
